﻿using BW.WMS.WareHouseStatistics.FileUpload;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;

namespace BW.WMS.WareHouseStatistics
{
    public class FileUploadAppService : ApplicationService, IFileUploadAppService
    {
        private readonly QiniuSettings _settings;

        public FileUploadAppService(IOptions<QiniuSettings> options)
        {
            _settings = options.Value;
        }

        public async Task<string> UploadFileToQiniuAsync(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                throw new ArgumentException("请选择有效的文件");
            }

            // 校验文件类型
            var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".txt", ".zip", ".rar" };
            var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            if (!allowedExtensions.Contains(fileExtension))
            {
                throw new ArgumentException("不支持的文件格式");
            }

            // 校验文件大小（10MB）
            if (file.Length > 10 * 1024 * 1024)
            {
                throw new ArgumentException("文件大小不能超过10MB");
            }

            try
            {
                // 生成唯一文件名
                var fileName = $"files/{DateTime.Now:yyyyMMddHHmmssfff}_{Guid.NewGuid()}{fileExtension}";

                // 读取文件内容
                using var stream = file.OpenReadStream();
                var fileBytes = new byte[file.Length];
                await stream.ReadAsync(fileBytes, 0, (int)file.Length);

                // 创建七牛云配置
                var config = new Config
                {
                    Zone = Zone.ZONE_CN_East, // 华东区域
                    UseHttps = true,
                    UseCdnDomains = true
                };

                // 创建七牛云上传管理器
                var uploadManager = new UploadManager(config);
                var mac = new Mac(_settings.AccessKey, _settings.SecretKey);
                var putPolicy = new PutPolicy
                {
                    Scope = _settings.Bucket
                };
                putPolicy.SetExpires(3600); // 1小时过期
                var uploadToken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());

                // 创建上传额外参数
                var putExtra = new PutExtra();

                // 上传文件
                var result = await Task.Run(() => uploadManager.UploadData(fileBytes, fileName, uploadToken, putExtra));

                if (result.Code == 200)
                {
                    // 返回文件访问URL
                    return $"{_settings.Domain}/{fileName}";
                }
                else
                {
                    // 如果上传失败，尝试使用其他区域
                    if (result.Text.Contains("incorrect region"))
                    {
                        // 尝试华南区域
                        config.Zone = Zone.ZONE_CN_South;
                        uploadManager = new UploadManager(config);
                        result = await Task.Run(() => uploadManager.UploadData(fileBytes, fileName, uploadToken, putExtra));

                        if (result.Code == 200)
                        {
                            return $"{_settings.Domain}/{fileName}";
                        }
                        else
                        {
                            // 尝试华北区域
                            config.Zone = Zone.ZONE_CN_North;
                            uploadManager = new UploadManager(config);
                            result = await Task.Run(() => uploadManager.UploadData(fileBytes, fileName, uploadToken, putExtra));

                            if (result.Code == 200)
                            {
                                return $"{_settings.Domain}/{fileName}";
                            }
                        }
                    }

                    throw new UserFriendlyException($"文件上传失败: {result.Text}");
                }
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException($"文件上传失败: {ex.Message}");
            }
        }
    }
}
